#include "forget.h"

forget::forget(QWidget *parent)
	: QWidget(parent)
{
	this->setWindowIcon(QIcon("Image\\运动会.svg"));
	QPixmap pixmap("Image\\光标.svg");
	pixmap = pixmap.scaled(30, 24, Qt::KeepAspectRatio);
	QCursor cursor(pixmap);
	this->setCursor(cursor);

	ui.setupUi(this);
	connect(ui.find, &QPushButton::clicked, this, &forget::changepasswords);
}

forget::~forget()
{}

void clearFile(const QString& filename) {
	QFile file(filename);
	if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {  // Truncate 模式会清空文件
		qWarning("无法打开文件 %s 进行清空操作", qUtf8Printable(filename));
		return;
	}
	file.close();  // 打开后立即关闭（Truncate 模式已清空内容）
}

void forget::changepasswords() {
	QString fileName = "../schoolInfo.txt";
	loadFile(schoolName, passwords, question, anwser, fileName);
	readPassword = ui.password->text();
	readSchool = ui.schoolName->text();
	readQuestion = ui.questionBox->currentText();
	readAnwser = ui.anwser->text();
	int flag = 1;
	for (int i = 0;i < schoolName.size();i++) {
		if (schoolName[i] == readSchool && readQuestion == question[i] && readAnwser == anwser[i]) {
			passwords[i] = readPassword;
			flag = 0;
		}
	}
	if (flag) {
		message("提示", "输入信息有误，请检查！", QMessageBox::Icon::Warning, QMessageBox::Ok, this);
	}
	else {
		clearFile(fileName);
		saveFile(schoolName, passwords, question, anwser, fileName);
		message("提示", "已成功找回！", QMessageBox::Icon::Information, QMessageBox::Ok, this);
		this->close();
	}

}
void forget::paintEvent(QPaintEvent* event) {
	QPainter painter(this);
	QString imagePath = "image\\背景4.jpg";

	// 检查路径是否存在
	if (!QFile::exists(imagePath)) {
		qDebug() << "图片文件不存在：" << imagePath;
	}
	else {
		QPixmap bkgnd(imagePath);
		if (bkgnd.isNull()) {
			qDebug() << "无法加载图片：" << imagePath;
			painter.fillRect(rect(), QColor("#2c3e50"));

			painter.setPen(Qt::white);
			painter.drawText(rect(), Qt::AlignCenter, "背景加载失败");
			return;
		}
		// 确认窗口有效尺寸
		if (width() <= 0 || height() <= 0) {
			qDebug() << "无效窗口尺寸：" << size();
			return;
		}

		// 高质量缩放
		bkgnd = bkgnd.scaled(size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
		painter.setOpacity(0.7);  //0.7
		painter.drawPixmap(0, 0, bkgnd);
	}
}